package cn.iocoder.yudao.module.shop.admin.controller.app;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.biz.config.ConfigCommonApi;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.api.infrastructure.config.ConfigApiV2;
import cn.iocoder.yudao.module.api.infrastructure.config.dto.MallConfigRespDTO;
import cn.iocoder.yudao.module.api.infrastructure.user.AdminUserApiV2;
import cn.iocoder.yudao.module.shop.admin.pojo.po.ShopUser;
import cn.iocoder.yudao.module.shop.admin.pojo.vo.AppShopUserAccountRespVO;
import cn.iocoder.yudao.module.shop.admin.service.ShopUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserType;
import static cn.iocoder.yudao.module.api.infrastructure.ConfigConstants.CONFIG_ACCOUNT_INIT_PASSWORD;
import static cn.iocoder.yudao.module.api.infrastructure.ConfigConstants.CONFIG_MALL;

@Tag(name = "用户 App - 店铺商户")
@RestController
@RequestMapping("/shop/admin")
@Validated
public class AppShopUserController {

    @Resource
    private ShopUserService shopUserService;
    @Resource
    private AdminUserApiV2 adminUserApiV2;
    @Resource
    private ConfigCommonApi configApi;
    @Resource
    private ConfigApiV2 configApiV2;

    @Value("${yudao.web.admin-ui.url")
    private String adminUiUrl;

    @GetMapping("/get-account")
    @Operation(summary = "获得店铺后台管理员账号信息")
    public CommonResult<AppShopUserAccountRespVO> getAdminAccount() {
        AppShopUserAccountRespVO respVO = new AppShopUserAccountRespVO();
        MallConfigRespDTO config = configApiV2.getConfig(CONFIG_MALL, MallConfigRespDTO.class);
        if (StrUtil.isNotBlank(config.getAdminUrl())) {
            respVO.setUrl(config.getAdminUrl());
        } else {
            respVO.setUrl(adminUiUrl);
        }
        String initPassword = configApi.getConfigValueByKey(CONFIG_ACCOUNT_INIT_PASSWORD);
        respVO.setTips("初始密码为：%s，请修改后使用。".formatted(initPassword));
        ShopUser shopUser = shopUserService.getLastAdminByUserId(getLoginUserId(), getLoginUserType());
        if (shopUser == null) {
            respVO.setUsername("无");
        } else {
            String username = adminUserApiV2.getUsernameById(shopUser.getAdminUserId());
            respVO.setUsername(username);
        }
        return success(respVO);
    }

}
